<script lang="ts" setup>
import type { RouteLocationRaw } from 'vue-router';

import config from '@/config';
import rawLinks from '@/router';
import type { Link } from '@/types/route';

interface ActivateLink extends Link {
  activate?: boolean;
  children?: ActivateLink[];
}

const { title } = config;

const useMergeLink = () => {
  const route = useRoute();

  const mergeLink = (
    links: typeof rawLinks,
    splitPath: string[],
    level: number
  ): ActivateLink[] => {
    return links.map((link) => {
      if (level > 2) {
        return link;
      }

      const { to, children } = link;
      const checkPath = level === 1 ? `/${splitPath[level]}` : splitPath[level];

      if (!children) {
        return { ...link, activate: link.to === checkPath };
      }

      const newChildren = mergeLink(children, splitPath, level + 1);

      return { ...link, children: newChildren, activate: to === checkPath };
    });
  };

  const mergedLink = reactive<ActivateLink[]>([]);
  const opened = ref<string[]>([]);

  onMounted(() => {
    const splitPath = route.path.split('/');

    const tmpLink = mergeLink(rawLinks, splitPath, 1);
    mergedLink.splice(0, mergedLink.length);
    mergedLink.push(...tmpLink);

    opened.value.push(
      ...tmpLink.filter((link) => link.activate).map((item) => item.title)
    );
  });

  watch(route, () => {
    const splitPath = route.path.split('/');
    mergedLink.splice(0, mergedLink.length);
    mergedLink.push(...mergeLink(rawLinks, splitPath, 1));
  });

  return { opened, mergedLink };
};

const useAuthCheck = () => {
  // const route = useRoute();
  // const path = route.path;

  onMounted(() => {
    // if (path === '/') {
    //   navigateTo('/home');
    // }
  });
};

const draw = ref(false);

useAuthCheck();
const { opened, mergedLink } = useMergeLink();

const navItemClick = async (title: string[]) => {
  const findPath = (
    layer: number,
    link: typeof rawLinks,
    path: RouteLocationRaw[]
  ): RouteLocationRaw => {
    if (layer >= title.length) {
      return path.join('/');
    }

    const item = link.find((item) => item.title === title[layer]);
    if (!item) {
      return path.join('/');
    }

    return findPath(layer + 1, item.children || [], [...path, item.to]);
  };

  const path = findPath(0, rawLinks, []);
  await navigateTo(path);
};
</script>

<template>
  <v-layout>
    <v-app-bar>
      <v-app-bar-nav-icon @click="draw = !draw" />
      <v-app-bar-title>
        <div class="h-full flex items-center">
          <!-- <nuxt-img src="/logo.png" class="h-12" /> -->
          <img src="/logo.png" class="h-12">
          <div class="text-h4">{{ title }}</div>
        </div>
      </v-app-bar-title>
    </v-app-bar>

    <v-navigation-drawer :rail="draw" permanent>
      <v-list v-model:opened="opened" density="compact" nav>
        <template v-for="link in mergedLink" :key="link.title">
          <v-list-item
            v-if="!link.children"
            :active="link.activate"
            :prepend-icon="link.icon"
            :title="link.title"
            color="primary"
            slim
            @click="() => navItemClick([link.title])"
          />

          <v-list-group v-else :value="link.title">
            <template #activator="{ props }">
              <v-list-item
                v-bind="props"
                :prepend-icon="link.icon"
                :title="link.title"
                slim
              />
            </template>

            <v-list-item
              v-for="child in link.children"
              :key="child.title"
              :active="child.activate"
              :title="child.title"
              color="primary"
              slim
              @click="() => navItemClick([link.title, child.title])"
            />
          </v-list-group>
        </template>
      </v-list>
    </v-navigation-drawer>

    <v-main>
      <v-container>
        <slot />
      </v-container>

      <v-footer>
        <v-row>
          <v-col class="text-center">
            {{ new Date().getFullYear() }} - <strong>{{ title }}</strong>
          </v-col>
        </v-row>
      </v-footer>
    </v-main>
  </v-layout>
</template>
